package http

import (
	"fmt"
	stdnet "net"
	"net/http"
	"sync"

	"engine/internal"
	net "gitee.com/ameise84/e3net"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrade = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

type httpServer struct {
	opts    internal.Options
	ln      stdnet.Listener
	srv     *gin.Engine
	connMap sync.Map
}

func (ts *httpServer) E3LogMarshall() string {
	return fmt.Sprintf("ws server[%ts]", ts.opts.Addr)
}

func (ts *httpServer) create(opts internal.Options) (err error) {
	ts.srv = _gHttpEngine

	var ip, port string
	if ip, port, err = net.SplitHostPort(opts.Addr); err != nil {
		return err
	}
	//如果没有指定地址,则只监听外网
	if ip == "" {
		ip = net.GetExternalIP()
	}
	//没有指定端口,默认分配
	if port == "" {
		port = "0"
	}
	opts.Addr = ip + ":" + port
	ts.opts = opts
	return nil
}

func (ts *httpServer) destroy() {
	ts.ln = nil
	ts.srv = nil
}

func (ts *httpServer) start() (addr string, err error) {
	ln, err := stdnet.Listen("tcp", ts.opts.Addr)
	if err != nil {
		return "", err
	}
	ts.ln = ln
	go func() {
		err = ts.srv.RunListener(ts.ln)
	}()

	return ln.Addr().String(), err
}

func (ts *httpServer) stop() {
	_ = ts.ln.Close()
}
